﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AK.FTP.Core;
using System.Collections;
using System.IO;
using EnterpriseDT.Net.Ftp;

namespace AK.FTP
{
    public partial class FrmFtpSync : Form
    {
        public FrmFtpSync()
        {
            InitializeComponent();
        }

        //开始同步
        private void btnStartSync_Click(object sender, EventArgs e)
        {
            DisplayStatus("正在验证");
            if (string.IsNullOrEmpty(txtLocalPath.Text))
            {
                MessageBox.Show("本地目录不能为空");
                return;
            }

            if (!Directory.Exists(txtLocalPath.Text))
            {
                MessageBox.Show("本地目录不存在");
                return;
            }
            DirectoryList.FileList.Clear();
            DirectoryList.GetDirectory(txtLocalPath.Text);
            if (DirectoryList.FileList.Count == 0)
            {
                MessageBox.Show("本地目录无文件");
                return;
            }
            DisplayStatus("正在连接");
            //TODO:检查FTP
            Connect();
            DisplayStatus("正在下载");
            StartDownload(DirectoryList.FileList);
            DisplayStatus(string.Empty);
        }

        //开始下载
        private void StartDownload(ArrayList fileList)
        {
            this.Cursor = Cursors.WaitCursor;
            tssBar.Visible = true;
            tssBar.Step = 1;
            tssBar.Maximum = fileList.Count;
            tssBar.Minimum = 0;

            string rootPath = txtLocalPath.Text.Replace("\\", "/");
            string path = string.Empty;
            int index = -1;
            string fileName = string.Empty;
            string filePath = string.Empty;
            foreach (string item in fileList)
            {
                path = item.Replace("\\", "/").Replace(rootPath, "");
                index = path.LastIndexOf("/");

                if (index > -1)
                {
                    filePath = path.Substring(0, index + 1);
                    fileName = path.Substring(index + 1);
                    if (!ftpConn.DirectoryExists(filePath))
                    {
                        DisplayLog(string.Format("文件目录[{0}]不存在", filePath), MessageTypeEnum.Error);
                        continue;
                    }
                    ftpConn.ChangeWorkingDirectory(filePath);
                    if (!ftpConn.Exists(fileName))
                    {
                        DisplayLog(string.Format("文件[{0}]不存在", fileName), MessageTypeEnum.Error);
                        continue;
                    }
                    ftpConn.DownloadFile(item, fileName);
                }
            }
            tssBar.Value = 0;
            tssBar.Visible = false;
            this.Cursor = Cursors.Default;
        }

        //连接
        private void Connect()
        {
            if (!ftpConn.IsConnected)
            {
                ftpConn.ServerAddress = GlobalValue.FTP_Server;
                ftpConn.UserName = GlobalValue.FTP_UserName;
                ftpConn.Password = GlobalValue.FTP_Password;
                ftpConn.ServerPort = GlobalValue.FTP_Port;
                ftpConn.Connect();
            }
        }

        private void Disconnect()
        {
            if (ftpConn.IsConnected)
            {
                //ftpConn.Exists()  
                ftpConn.Close();
            }
        }

        private void DisplayStatus(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                tssStatus.Text = "就绪";
            }
            else
            {
                tssStatus.Text = msg;
            }
        }

        //显示日志记录
        private void DisplayLog(string msg, MessageTypeEnum type)
        {
            msg = string.Format("[{0}]{1}", DateTime.Now, msg);
            if (string.IsNullOrEmpty(msg))
                return;

            txtLog.SelectionStart = txtLog.Text.Length - msg.Length;
            //txtLog.SelectionLength = msg.Length;
            txtLog.SelectionColor = type == MessageTypeEnum.Error ? Color.Red : Color.DodgerBlue;
            txtLog.AppendText("\r\n" + msg);
            txtLog.ScrollToCaret();
        }

        private void DisplayLog(string msg)
        {
            DisplayLog(msg, MessageTypeEnum.Normal);
        }

        private void ftpConn_Closed(object sender, EnterpriseDT.Net.Ftp.FTPConnectionEventArgs e)
        {
            if (!e.IsConnected)
            {
                DisplayLog(string.Format("[{0}]成功断开连接", e.ServerAddress));
            }
        }

        private void ftpConn_Connected(object sender, EnterpriseDT.Net.Ftp.FTPConnectionEventArgs e)
        {
            if (e.IsConnected)
            {
                DisplayLog(string.Format("[{0}]连接成功", e.ServerAddress));
            }
            else
            {
                DisplayLog(string.Format("[{0}]连接失败", e.ServerAddress), MessageTypeEnum.Error);
            }
        }

        private void ftpConn_Downloaded(object sender, EnterpriseDT.Net.Ftp.FTPFileTransferEventArgs e)
        {
            DisplayLog(string.Format("文件[{0}]下载成功...", e.RemoteFileName));
            tssBar.PerformStep();
        }

        private void ftpConn_Downloading(object sender, EnterpriseDT.Net.Ftp.FTPFileTransferEventArgs e)
        {

        }

    }

    public class DirectoryList
    {
        /*利用静态数据来存储文件路径列表*/
        private static ArrayList directorysList = new ArrayList();//存储目录列表数据

        public static ArrayList DirectorysList
        {
            get { return DirectoryList.directorysList; }
            set { DirectoryList.directorysList = value; }
        }
        private static ArrayList fileList = new ArrayList();//存储文件路径列表

        public static ArrayList FileList
        {
            get { return DirectoryList.fileList; }
            set { DirectoryList.fileList = value; }
        }
        public static void GetDirectory(string sourcePath)
        {
            if (Directory.Exists(sourcePath))//判断源文件夹是否存在
            {
                string[] tmp = Directory.GetFileSystemEntries(sourcePath);//获取源文件夹中的目录及文件路径，存入字符串
                //循环遍历
                for (int i = 0; i < tmp.Length; i++)
                {
                    if (File.Exists(tmp[i]))//如果是文件则存入FileList
                    {
                        FileList.Add(tmp[i]);
                    }
                    else
                    {
                        if ((Directory.GetDirectories(tmp[i])).Length == 0)//如果是最后一层目录则把其路径存入DirectorysList
                        {
                            DirectorysList.Add(tmp[i]);
                        }
                    }
                    //递归开始.......
                    GetDirectory(tmp[i]);
                }
            }
        }
    }
}
